import {
	requestURL,
	PMCP_URL
} from './config'
import {
	toQueryString
} from '@/common/utils/util.js' //组件用正则 过滤传递的参数
// 请求头
let header = {
	"ClientType": 'psychology',
	"content-type": "application/json;charset=UTF-8",
}

// 获取请求方式
function getType(data, method) {
	let type = {}
	if (method === 'POST') {
		type = {
			method,
			dataType: 'json',
			data: {
				...data
			},
			header: {
				...header,
				'Authorization': "Bearer " + uni.getStorageSync('ttToken')
			}
		}
	} else {
		type = {
			method,
			dataType: 'json',
			data: JSON.stringify({
				...data
			}),
			header: {
				...header,
				'Authorization': "Bearer " + uni.getStorageSync('ttToken')
			}
		}
	}
	return type
}

function Request(data, url, method) {
	let BASE_URL
	if (url.includes('getStsTokenInfo')) {
		BASE_URL = PMCP_URL
		header["content-type"] = "application/x-www-form-urlencoded;charset=UTF-8"
	} else {
		BASE_URL = requestURL
		header["content-type"] = "application/json;charset=UTF-8"
	}
	if (method === 'GET' && data) {
		url = url + toQueryString(data);
	}
	console.log(JSON.stringify(data));
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '加载中'
		})
		uni.request({
			url: BASE_URL + url,
			...getType(data, method),
			success: res => {
				uni.hideLoading()
				console.log(BASE_URL + url + '==')
				console.log(res)
				let data = res.data;
				var codeString = data.code + "";
				// 如果返回结果的res.data.code 中有10110,1016002 或者等于500 就提示登录凭证失效,跳转到登录页   并清除本地存的用户信息
				if (codeString.includes('10110') || codeString == 500 || codeString.includes(
						'1011006')) {
					console.log("接口调用凭证已失效")
					// uni.navigateTo({
					// 	url: '/subcontractorA/authorization/authorization',
					// 	complete(e) {
					// 		uni.clearStorageSync()
					// 	}
					// })
				} else {
					resolve(res)
				}
			},
			fail: err => {
				uni.hideLoading()
				reject(err)
			}
		})
	}).catch(err => console.log(err))
}


export default function(data, url, method) {
	return Request(data, url, method)
}